using System;
using System.Diagnostics;
using System.Collections;
using System.IO;

//using System.Windows.Forms;
using CIndicators;
using CStock;
using CUtil;


namespace CStock
{
	/// <summary>
	/// Summary description for TradeStepFactory.
	/// </summary>
	public class TradeStepFactory 
	{
		
		private static bool bMultipleAssertionError;
        private static IProgramContext programContext;
        

        public TradeStepFactory()
		{
			

        }
    

        #region Step helpers
        private static void CheckAbort()
        {
            //if the trade system has an internal error 
            if (TradeSystemStaticFunctions.Abort)
            {
                TradeStepFactory.ProgramContext.Configuration.TerminateAction = true;
                return;
            }
            System.Windows.Forms.Application.DoEvents();
        }
        private static void AdjustDynamicStopLossLimit( IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;

            //if we have a dynamic stop win/loss:
            if (TradeStepFactory.ProgramContext.Configuration.TradeStopLossDynamic)
            {

                double q = myTradeStep.QuoteShare;

                double f = q - myTradeStep.QuoteLastDay;
                //adjust the limit dynamically only when the quote is rising
                if (f > 0F)
                {
                    //calculate the new limit
                    f = q * (100F - TradeStepFactory.ProgramContext.Configuration.TradeStopLossDynamicPercentage) / 100F;

                    //set the limit only when it is larger than the existing one
                    if (f > myTradeStep.TradeStopLossDynamicLimit)
                    {
                        //this would be the new limit
                        myTradeStep.TradeStopLossDynamicLimit = f;
                    }

                }


            }
            
        }
        private static void CheckMultipleAssertionErrorQuoteZero( IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;

            if (myTradeStep.QuoteShare == 0)
            {
                if (!bMultipleAssertionError)
                {
                    System.Diagnostics.Debug.Assert(false, "ShareQuote = 0 - error in data ?");
                }
                bMultipleAssertionError = true;
                return;

            }
            bMultipleAssertionError = false;
        }
        private static bool GetValidDate(IDataItem myDataItem)
        {
            myDataItem.TradeStep.Date = myDataItem.DataClass.DateOf(myDataItem.TradeStep.DateIndex);
            if (myDataItem.TradeStep.DateIndex >= (myDataItem.DataClass.QuoteCollection.Count))
                return false;
            return true;

        }
        private static void SetDataFor_TradeStepStopWin( IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;

            //set the quoteShareMaxSinceLastTrade etc. for the option TradeStepStopWin
            if (TradeStepFactory.ProgramContext.Configuration.TradeStopWin)
            {
                //remember to reset them if a buy/sell occurs !
                if (myTradeStep.QuoteShare > myTradeStep.QuoteShareLastTrade)
                {
                    if (myTradeStep.QuoteShare > myTradeStep.QuoteShareMaxSinceLastTrade)
                    {
                        myTradeStep.QuoteShareMaxSinceLastTrade = myTradeStep.QuoteShare;
                    }
                }
                else if (myTradeStep.QuoteShare < myTradeStep.QuoteShareLastTrade)
                {
                    if (myTradeStep.QuoteShare < myTradeStep.QuoteShareMinSinceLastTrade)
                    {
                        myTradeStep.QuoteShareMinSinceLastTrade = myTradeStep.QuoteShare;
                    }

                }
            }
        }
        #endregion

        public static void Step(IDataItem myDataItem) 
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
            CheckAbort();
            AdjustDynamicStopLossLimit(myDataItem);

            if (!GetValidDate(myDataItem))
                return;


            CheckMultipleAssertionErrorQuoteZero(myDataItem);
            SetDataFor_TradeStepStopWin(myDataItem);

            myTradeStep.IndicatorsString = string.Empty;

            if (!StepBuy(myDataItem))
                StepSell(myDataItem);
	
			
		}
        private static double Calculate_Buy_MoneyNecessary(IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;
            //1. Calculate the minimal transaction costs
            //double qShare = myTradeStep.QuoteShare;
            //int numberOfSharesFor1000Trade = 10000/qShare;
            double MyMoneyNecessary = 0F;
            if (TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
            {
                MyMoneyNecessary = myTradeStep.FuturesContractValue + myTradeStep.FuturesBankCost;
            }
            else
            {
                MyMoneyNecessary = myTradeStep.QuoteShare + myTradeStep.MinimalTransactionCost;
            }
            return MyMoneyNecessary;
        }
        private static bool BuyOccured(IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;
            Evaluate_NumberOfShares_Buy(myDataItem);
            //------------------------------------------------------------


            //BUY OCCURS!!!
            if (myTradeStep.NumberOfSharesTraded != 0)
            {
                Step_TradeEvaluations(myDataItem, false);
                return true;

            }
            return false;
        }
        private static bool StopLossOccured(IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;
            myTradeStep.TradeType = TradeType.BuyStopLoss;
            myTradeStep.NumberOfSharesTraded = -myTradeStep.NumberOfShares;
            Step_TradeEvaluations(myDataItem, false);
            return true;
        }
        #region StepBuy helpers

        private static bool Check_Buy(IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;
            //result got as myTradeStep.TradeType
            if (myTradeStep.TradeType != CUtil.TradeType.Nothing)
            {
                if (BuyOccured(myDataItem))
                    return true;
            }
            return false;

        }
        private static bool Check_Buy_StopLoss(IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;
            //4. StopLoss buy shares (stopLoss)
            if (myTradeStep.NumberOfShares < 0 && TradeStepFactory.ProgramContext.Configuration.TradeStopLoss && myTradeStep.QuoteShare / myTradeStep.QuoteShareLastTrade > (1 + (double)TradeStepFactory.ProgramContext.Configuration.TradeStopLossPercentage / (double)100))
            {
                return StopLossOccured(myDataItem);

            }
            return false;

        }
       
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static bool StepBuy(IDataItem myDataItem)
		{
            //ITradeStep myTradeStep = myDataItem.TradeStep;
            double MyMoneyNecessary = Calculate_Buy_MoneyNecessary(myDataItem);
            EvaluateBuyConditions(myDataItem, MyMoneyNecessary);

            //the trade type to be executed is given in
            //System.Diagnostics.Debug.WriteLine(myTradeStep.TradeType.ToString());
            //Trade event given in myTradeStep.TradeEvents


            if (Check_Buy(myDataItem))
                return true;

            if (Check_Buy_StopLoss(myDataItem))
                return true;

            if (Check_Buy_StopLoss(myDataItem))
                return true;
                
			return false;
        }
        #region StepSell helpers

        //private static double Calculate_Sell_MoneyNecessary(IDataItem myDataItem)
        //{
        //    ITradeStep myTradeStep = myDataItem.TradeStep;

            
        //    //1. Calculate the minimal transaction costs
        //    //double qShare = myTradeStep.QuoteShare;
        //    //int numberOfSharesFor1000Trade = 10000/qShare;

        //    double MyMoneyNecessary = 0F;
        //    if (TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
        //    {
        //        MyMoneyNecessary = myTradeStep.FuturesContractValue + myTradeStep.FuturesBankCost;
        //    }
        //    else
        //    {
        //        MyMoneyNecessary = myTradeStep.QuoteShare + myTradeStep.MinimalTransactionCost;
        //    }
        //    return MyMoneyNecessary;
        //}
        private static bool Check_Sell( IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;

            //2. sell shares because sell indicators conditions permit this
            if (myTradeStep.TradeType != CUtil.TradeType.Nothing)
            {
                Evaluate_NumberOfShares_Sell(myDataItem);
                return true;

            }
            return false;

        }
        private static bool Check_Sell_StopLoss( IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;

            //4. Sell shares: stopLoss 
            if (TradeStepFactory.ProgramContext.Configuration.TradeStopLoss &&
                myTradeStep.QuoteShareLastTrade / myTradeStep.QuoteShare > (1 + (double)TradeStepFactory.ProgramContext.Configuration.TradeStopLossPercentage / (double)100))
            {

                myTradeStep.TradeType = TradeType.SellStopLoss;
                myTradeStep.NumberOfSharesTraded = -myTradeStep.NumberOfShares;
                Step_TradeEvaluations(myDataItem, false);
                return true;

            }
            return false;
            
        }
        private static bool Check_Sell_StopWin( IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;

            //5. Sell shares: stopWin 
            if (myTradeStep.NumberOfShares > 0 && TradeStepFactory.ProgramContext.Configuration.TradeStopWin && myTradeStep.QuoteShareLastTrade / myTradeStep.QuoteShare > (1 + (double)TradeStepFactory.ProgramContext.Configuration.TradeStopWinPercentage / (double)100))
            {

                myTradeStep.TradeType = TradeType.SellStopWin;
                myTradeStep.NumberOfSharesTraded = -myTradeStep.NumberOfShares;
                Step_TradeEvaluations(myDataItem, false);
                return true;

            }
            return false;

        }
        private static bool Check_Sell_StopLossDynamic(IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;
            //6. Sell shares: stopLossDynamic
            if (myTradeStep.NumberOfShares > 0 && TradeStepFactory.ProgramContext.Configuration.TradeStopLossDynamic
                && myTradeStep.QuoteShare < myTradeStep.TradeStopLossDynamicLimit)
            {

                myTradeStep.TradeType = TradeType.SellStopDynamic;
                myTradeStep.NumberOfSharesTraded = -myTradeStep.NumberOfShares;
                Step_TradeEvaluations(myDataItem, false);
                return true;

            }
            return false;
        }
        #endregion

        private static bool StepSell(IDataItem myDataItem)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;
            //double MyMoneyNecessary = Calculate_Sell_MoneyNecessary(myDataItem);

            EvaluateSellConditions(myDataItem);

            //the trade type to be executed is given in
            //System.Diagnostics.Debug.WriteLine(myTradeStep.TradeType.ToString());
            //Trade event given in myTradeStep.TradeEvents

            if (Check_Sell(myDataItem))
                return true;
           
            //3. Still shares in portfolio ?
            if (myTradeStep.NumberOfShares > 0)
            {
                if (Check_Sell_StopLoss(myDataItem))
                    return true;
                if (Check_Sell_StopWin(myDataItem))
                    return true;
                if (Check_Sell_StopLossDynamic(myDataItem))
                    return true;
                     
            }


            return false;
        }

        public static void StepPortfolio(IPortfolio myPortfolio, IGrid myGrid, bool intraday) 
		{
            for (int i = 0; i < myPortfolio.DataItems.Count; i++)
			{
                ITradeStep myTradeStep = myPortfolio.DataItems[i].TradeStep;
                IDataItem myDataItem = myPortfolio.DataItems[i];
                myPortfolio.TradeStepPortfolio.DataItem_SelectedForPortfolio = myPortfolio.DataItems[i];
                myPortfolio.TradeStepPortfolio.TradeWriteMode = TradeWriteModes.EachTradeStep;
                myPortfolio.TradeStepPortfolio.TradeWriteMode = TradeWriteModes.EachTradeStep;
                StepShare(myDataItem, myGrid, intraday); 
				myTradeStep.DateIndex ++;
				
			}

			
		}
        public static void EndEvaluations( ITradeStep myTradeStep, bool Isintraday)
		{
            if (Isintraday)
			{
				//string time = myTradeStep.Date.Hour.ToString() + ":" + myTradeStep.Date.Minute.ToString() + ":" +
					myTradeStep.Date.Second.ToString();
				//Grid TODO
				//myGrid.ListViewItemTrade[TradeListViewEnum.Date.ToString()] = time;
			
			}
			else
			{
				//Grid TODO
				//myGrid.ListViewItemTrade[TradeListViewEnum.Date.ToString()] = myTradeStep.Date.ToShortDateString();
			
			}
			//Grid TODO
//			myGrid.ListViewItemTrade[TradeListViewEnum.No.ToString()] = myTradeStep.DateIndex.ToString();
//			myGrid.ListViewItemTrade[TradeListViewEnum.Quote.ToString()] = myTradeStep.QuoteShare.ToString();
//			myGrid.ListViewItemTrade[TradeListViewEnum.TradesSuccesfull.ToString()] = myTradeStep.TradesSuccesfull.ToString() + "%(" + myTradeStep.TradesNumber.ToString() + ")";
//			
//
//			myGrid.ListViewItemTrade[TradeListViewEnum.NoShares.ToString()] = myTradeStep.NumberOfShares.ToString();

            if (Isintraday)
			{
				//Grid TODO
				//myGrid.ListViewItemTrade[TradeListViewEnum.PerformancePerYear.ToString()] = 	myTradeStep.PerformanceIntraday.ToString();
		
			}
			else
			{
				//Grid TODO
				//myGrid.ListViewItemTrade[TradeListViewEnum.PerformancePerYear.ToString()] = 	myTradeStep.PerformancePerYear.ToString();
		
			}
			//Grid TODO
//			myGrid.ListViewItemTrade[TradeListViewEnum.RelPerformance.ToString()] = 	myTradeStep.PerformanceRelativePerYear.ToString();																				
//			myGrid.ListViewItemTrade[TradeListViewEnum.PortfolioValue.ToString()] = myTradeStep.ValueTotal.ToString();
//		
//			
//			myGrid.ListViewItemTrade[TradeListViewEnum.Indicators.ToString()]= myTradeStep.Indicators ;

			if(myTradeStep.TradeType == TradeType.Nothing)
			{
				//myGrid.ListViewItemTrade[TradeListViewEnum.BuySell.ToString()] = "--";
			}
			else
			{
				//myGrid.ListViewItemTrade[TradeListViewEnum.BuySell.ToString()] = myTradeStep.TradeType.ToString();
			}

		}
        public static bool AdjustSimulationLimits(IDataItem myDataItem, out DateTime dateMin, out DateTime dateMax, bool intraday)
        {
            //ITradeStep myTradeStep = myDataItem.TradeStep;
            dateMin = new DateTime(1, 1, 1);
            dateMax = new DateTime(1, 1, 1);

            IListQuotes qColl = myDataItem.DataClass.QuoteCollection;
            try
            {
                if (intraday)
                {
                    IListQuotes qc = myDataItem.DataClass.QuoteCollection;


                    if (!((qc != null) && (qc.Count > 0)))
                    {
                        qc = myDataItem.DataClass.QuoteCollection;

                        
                    }
                    Debug.Assert((qc != null) && (qc.Count > 0));
                    dateMin = qc[0].DATE;
                    dateMax = qc[qc.Count - 1].DATE;
                    return true;

                }
                else
                {
                    dateMin = TradeStepFactory.ProgramContext.Configuration.Dates.DateMinSimulation;
                    dateMax = TradeStepFactory.ProgramContext.Configuration.Dates.DateMaxSimulation;
                   
                    //no adjustment
                    if (qColl != null && qColl.Count > 0)
                    {


                        DateTime lastDate = qColl[qColl.Count - 1].DATE;
                        DateTime firstDate = qColl[0].DATE;

                        //see if we have enough data to move
                        if (dateMax > lastDate)
                        {

                            Debug.WriteLine("Warning : Simulation for share " + myDataItem.DataClass.Name + " : share data only available untill " +
                                lastDate.ToShortDateString() + " - requested simulation would have ended at " + dateMax.ToShortDateString());
                            dateMax = lastDate;

                        }
                        if (dateMin < firstDate)
                        {
                            Debug.WriteLine("Warning : Simulation for share " + myDataItem.DataClass.Name + " : share data only available from " +
                                firstDate.ToShortDateString() + " - requested simulation would have started at " + dateMin.ToShortDateString());
                            dateMin = firstDate;
                            //this.configuration.Dates.DateMaxChartCurrent = this.configuration.Dates.DateMinChartCurrent.Add(ts);
                        }


                        return true;
                    }
                    else
                    {
                        Debug.WriteLine("Data class not initialized (no OHLC-s) when adjusting limits for " + myDataItem.DataClass.Name);
                        return false;

                    }
                }
            }
            catch (Exception exc)
            {
                Debug.Assert(false, "Error resetting limits ", exc.Message);
                return false;
            }

        }
		public static bool ResetTradeStepToDates(IDataItem myDataItem, bool intraday)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;

			DateTime dMin ;
			DateTime dMax;
            if (!AdjustSimulationLimits(myDataItem , out dMin, out dMax, intraday))
				return false;//during program start
			myTradeStep.DateMin  = dMin;
			myTradeStep.DateMax = dMax;
            myTradeStep.DateMinIndex = myDataItem.DataClass.IndexFindGreaterThan(myTradeStep.DateMin);
            myTradeStep.DateMaxIndex = myDataItem.DataClass.IndexFindSmallerThanStartEnd(myTradeStep.DateMax);

            myTradeStep.Intraday = intraday;

			myTradeStep.Date = myTradeStep.DateMin;

			myTradeStep.DateIndex = myTradeStep.DateMinIndex ;//start from 0 // or a day less than first day - e.g. -1 ??
			myTradeStep.TradeEvents = new System.Collections.ArrayList();
			
			return true;

		}
	
		private static void Step_TradeEvaluations( IDataItem myDataItem, bool optionsTrade)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;

			//rest dynamic limit for stop loss
			if(TradeStepFactory.ProgramContext.Configuration.TradeStopLossDynamic)
			{
				double f = myTradeStep.QuoteShare * (100F - TradeStepFactory.ProgramContext.Configuration.TradeStopLossDynamicPercentage) / 100F;
				myTradeStep.TradeStopLossDynamicLimit = f;
			}
			
			if(TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
			{
                Step_TradeEvaluations_Futures(myDataItem);
			}
			else
			{
                Step_TradeEvaluations_Share(myDataItem, optionsTrade);
			}
		}
        private static void Step_TradeEvaluations_Futures(IDataItem myDataItem)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
			//-------------------------------
			//TransactionCosts > 0 if I sell (I get the money)
			//TransactionCosts < 0 if I buy (I spend the money)

			//myTradeStep.NumberOfSharesTraded > 0 for buy
			//myTradeStep.NumberOfSharesTraded < 0 for sell
		
			myTradeStep.QuoteShareLastTrade = myTradeStep.QuoteShare;
			int i = Convert.ToInt32(myTradeStep.QuoteShare - myTradeStep.QuoteShareLastTrade);
			//int j = Convert.ToInt32(myTradeStep.QuoteShare);
			double transaction = - myTradeStep.NumberOfSharesTraded * myTradeStep.FuturesContractValue ;		
			double winMoney = - myTradeStep.NumberOfSharesTraded  * i * myTradeStep.FuturesMoneyPerTick;

			myTradeStep.TransactionCosts = transaction;


			if(myTradeStep.NumberOfSharesTraded != 0)
			{
			
				switch(myTradeStep.TradeType)
				{
					
					case (CUtil.TradeType.BuyShort):
					{
						myTradeStep.TransactionCosts += winMoney;
						break;
						//get money
					}
					case (CUtil.TradeType.Sell):
					{
						myTradeStep.TransactionCosts += winMoney;
						break;
						//get money
					}
					case (CUtil.TradeType.SellStopWin):
					{
						myTradeStep.TransactionCosts += winMoney;
						break;
						//get money
					}
					case (CUtil.TradeType.SellStopLoss):
					{
						myTradeStep.TransactionCosts += winMoney;
						break;
						//get money
					}
					case (CUtil.TradeType.SellStopDynamic):
					{
						myTradeStep.TransactionCosts += winMoney;
						break;
						//get money
					}
					default:
					{
						break;

					}
				}
				
				//determine if positive or negative trade:
				
				//				myTradeStep.TransactionCosts =  - myTradeStep.NumberOfSharesTraded * j;//this.futuresMoneyPerTick;
				//				//myTradeStep.TransactionCosts =  - myTradeStep.NumberOfSharesTraded * this.futuresContractValue ;//+ this.futuresMoneyPerTick;
				//				myTradeStep.TransactionCosts += i * futuresMoneyPerTick;

                EvaluateBankCosts(myDataItem);
				//myTradeStep.BankingCosts = - Math.Abs(myTradeStep.NumberOfSharesTraded) * myTradeStep.FuturesBankCost;
				myTradeStep.TransactionCosts += myTradeStep.BankingCosts;

				myTradeStep.TotalBankingCosts +=myTradeStep.BankingCosts;
				myTradeStep.NumberOfShares += myTradeStep.NumberOfSharesTraded;
			}

			myTradeStep.Money += myTradeStep.TransactionCosts ;
					
			if(myTradeStep.TradeWriteMode == TradeWriteModes.EachTradeStep ||
				myTradeStep.TradeWriteMode == TradeWriteModes.OnlyTrade)
			{
				//Grid TODO
				//myGrid.ListViewItemTrade[TradeListViewEnum.NoShares.ToString()] = myTradeStep.NumberOfSharesTraded;
			}
            AddTradeEvent(myDataItem);
			
		}
        private static void EvaluateBankCosts(IDataItem myDataItem)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
            
			myTradeStep.BankingCosts =  - Math.Abs( myTradeStep.TransactionCosts) *  myTradeStep.ConstSingleTransactionPercentageCost/ 100 ;
			if(myTradeStep.BankingCosts > myTradeStep.MinimalTransactionCost)
			{
				myTradeStep.BankingCosts = myTradeStep.MinimalTransactionCost;
			}
			if(myTradeStep.BankingCosts < myTradeStep.MaximalTransactionCost)
			{
				myTradeStep.BankingCosts = myTradeStep.MaximalTransactionCost;
			}
		}

        private static void EvalBankCosts(ITradeStep myTradeStep, IDataItem myDataItem)
        {
            if (myTradeStep.NumberOfSharesTraded != 0)
            {

                if (TradeStepFactory.ProgramContext.Configuration.TradeMoneyType == CUtil.TradeMoneyType.TradeOneShare)
                {
                    myTradeStep.BankingCosts = myTradeStep.QuoteShare * myTradeStep.BankingCostsPercentage / 100;
                   
                    
                }
                else
                {
                   
                    EvaluateBankCosts(myDataItem);

                }
                //-------------------------------
                //TransactionCosts > 0 if I sell (I get the money)
                //TransactionCosts < 0 if I buy (I spend the money)

                //myTradeStep.NumberOfSharesTraded > 0 for buy
                //myTradeStep.NumberOfSharesTraded < 0 for sell
		
                    
                myTradeStep.TransactionCosts = -myTradeStep.NumberOfSharesTraded * myTradeStep.QuoteShare;
                //myTradeStep.BankingCosts =  - Math.Abs( myTradeStep.TransactionCosts) *  myTradeStep.ConstSingleTransactionPercentageCost/ 100 - myTradeStep.MinimalTransactionCost;
                myTradeStep.TransactionCosts += myTradeStep.BankingCosts;
                myTradeStep.TotalBankingCosts += myTradeStep.BankingCosts;
                myTradeStep.NumberOfShares += myTradeStep.NumberOfSharesTraded;
            }
            myTradeStep.QuoteShareLastTrade = myTradeStep.QuoteShare;
            myTradeStep.Money += myTradeStep.TransactionCosts;

            if (myTradeStep.TradeType == CUtil.TradeType.BuyOneShare)
            {
                myTradeStep.LastBuyTransaction = myTradeStep.TransactionCosts;
                myTradeStep.Money = 0f;

            }
          
            

        }
		private static void Step_TradeEvaluations_Share(IDataItem myDataItem, bool optionsTrade)
		{
        
            ITradeStep myTradeStep = myDataItem.TradeStep;
            EvalBankCosts(myTradeStep, myDataItem);
			
            

           
			if(optionsTrade)
			{
				myTradeStep.Money -= myTradeStep.FuturesBankCost * myTradeStep.BankingCosts ;
			}
			
			if(myTradeStep.TradeWriteMode == TradeWriteModes.EachTradeStep ||
				myTradeStep.TradeWriteMode == TradeWriteModes.OnlyTrade)
			{
				//Grid TODO
				//myGrid.ListViewItemTrade[TradeListViewEnum.NoShares.ToString()] = myTradeStep.NumberOfSharesTraded;
			}
            AddTradeEvent(myDataItem);
            
			
		}
        
           
        
		private static void EvaluateBuyConditions(IDataItem myDataItem, double MyMoneyNecessary)
		{
             ITradeStep myTradeStep = myDataItem.TradeStep;
             EvaluateBuyShort(myDataItem);

             if (TradeStepFactory.ProgramContext.Configuration.TradeMoneyType == CUtil.TradeMoneyType.TradeOneShare)
             {
             }
             else
             {
                 if (myTradeStep.Money < myTradeStep.MinmalTransactionAmount)
                 {
                     //myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Nothing;
                     return;
                 }
             }
			
			if(myTradeStep.TradeTypeMoneyPossible == CUtil.TradeType.Nothing)
			{
                EvaluateMoneyBuyConditions(myDataItem, MyMoneyNecessary);
				EvaluateBuyConditions(myTradeStep,  myTradeStep.TradeSystem);
				
			}
			
			
		}
      
        private static void EvaluateBuyShort( IDataItem myDataItem)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
			myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Nothing;
			myTradeStep.TradeType  = CUtil.TradeType.Nothing;
		
			//1. try to sell (buy back ) the options first
			if( TradeStepFactory.ProgramContext.Configuration.TradeShortSellAllowed)
			{
				if(myTradeStep.NumberOfShares < 0 )
				{
					myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.BuyShort;
					//return;
				}
				

			}
			//evaluate indicator condition:
			if(myTradeStep.TradeTypeMoneyPossible == CUtil.TradeType.BuyShort)
			{

                EvaluateBuyConditions(myTradeStep, myTradeStep.TradeSystem);
				if(myTradeStep.TradeTypeMoneyPossible == CUtil.TradeType.Nothing)
				{
					if(TradeStepFactory.ProgramContext.Configuration.TradeShortSellOtherFile)
					{
						EvaluateBuyConditions(myTradeStep,  myTradeStep.TradeSystemForShortSell);
					}
					else
					{
						EvaluateBuyConditions(myTradeStep,  myTradeStep.TradeSystem);
					}
				}
			}


		}
	
		private static void EvaluateMoneyBuyConditions( IDataItem myDataItem, double MyMoneyNecessary)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
			//--------------------------------------
			//Buy if
			//1. Option trading is allowed
			//2. The configured trade type is CUtil.TradeMoneyType.TradeWith10000
			//        - and we do not yet have shares in the portfolio
			//3. The configured trade type is CUtil.TradeMoneyType.TradeWith10000AllTheTime

			//			myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Nothing;
			//			myTradeStep.TradeType  = CUtil.TradeType.Nothing;

			//1.normal buy
            switch (TradeStepFactory.ProgramContext.Configuration.TradeMoneyType)
            {
                case CUtil.TradeMoneyType.TradeWithAllMoney:
                    {
                        myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Buy;
                        //return;
                        break;
                    }
                case CUtil.TradeMoneyType.TradeWith10000:
                    {
                        if (myTradeStep.NumberOfShares == 0 && myTradeStep.Money > MyMoneyNecessary)
                        {
                            myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Buy10000;

                        }
                        break;

                    }
                case CUtil.TradeMoneyType.TradeOneShare:
                    {
                        if (myTradeStep.NumberOfShares == 0)
                        {
                            myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.BuyOneShare;

                        }
                        break;

                    }
                case CUtil.TradeMoneyType.TradeWith10000AllTheTime:
                    {
                        myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Buy10000Again;
                        break;
                    }
            }
			
          
			
			
		}

		private static void EvaluateBuyConditions( ITradeStep myTradeStep, ITradeSystem tradeSystem)
		{
			
			//----------------------------------
			//evaluate second condition - if the indicators are OK
			if(myTradeStep.TradeTypeMoneyPossible != CUtil.TradeType.Nothing)
			{
              
                myTradeStep.BuySellOccurs = TradeSystemStaticFunctions.Static_BuyCondition
                    ( myTradeStep, tradeSystem);
				if(myTradeStep.BuySellOccurs)
					myTradeStep.TradeType = myTradeStep.TradeTypeMoneyPossible;

			}

		}

        private static void Evaluate_NumberOfShares_Sell( IDataItem myDataItem)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
			switch (myTradeStep.TradeType)
			{
				case (CUtil.TradeType.Sell):
				{
					//1.2 normal buy 
					// Calculate the number of shares to buy:(do not include the transaction cost as influencing the number of shares to buy
					if(TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
					{
						myTradeStep.NumberOfSharesTraded = - myTradeStep.NumberOfShares;
                        Step_TradeEvaluations(myDataItem, false);
					}
					else
					{
						myTradeStep.NumberOfSharesTraded = - myTradeStep.NumberOfShares;
                        Step_TradeEvaluations(myDataItem, false);
					}
					
					break;
				}
				case (CUtil.TradeType.SellShort10000):
				{
					if(TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
					{
						myTradeStep.NumberOfSharesTraded = -Convert.ToInt32(myTradeStep.MaxMoneyForBuyPerShare / myTradeStep.FuturesContractValue) ;	
						//virtually add money to the portfolio 
						//myTradeStep.Money -= 2 * myTradeStep.QuoteShare * myTradeStep.NumberOfSharesTraded ;
                        Step_TradeEvaluations(myDataItem, true);
					}
					else
					{
						myTradeStep.NumberOfSharesTraded = -Convert.ToInt32(myTradeStep.MaxMoneyForBuyPerShare / myTradeStep.QuoteShare) ;	
						//virtually add money to the portfolio 
						//myTradeStep.Money -= 2 * myTradeStep.QuoteShare * myTradeStep.NumberOfSharesTraded ;
                        Step_TradeEvaluations(myDataItem, true);
					}
					
					break;
				}
				case (CUtil.TradeType.SellShort10000Again):
				{
					if(TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
					{
						myTradeStep.NumberOfSharesTraded = -Convert.ToInt32(myTradeStep.MaxMoneyForBuyPerShare / myTradeStep.FuturesContractValue) ;
                        Step_TradeEvaluations(myDataItem, true);
					}
					else
					{
						myTradeStep.NumberOfSharesTraded = -Convert.ToInt32(myTradeStep.MaxMoneyForBuyPerShare / myTradeStep.QuoteShare) ;
                        Step_TradeEvaluations(myDataItem, true);
					}
					//myTradeStep.Money -= 2 * myTradeStep.QuoteShare * myTradeStep.NumberOfSharesTraded ;
					
					break;
				}
						
			}
            SellPerformanceForTradeOneShare(myTradeStep);

		}
        private static void SellPerformanceForTradeOneShare(ITradeStep myTradeStep)
        {
            if (TradeStepFactory.ProgramContext.Configuration.TradeMoneyType == CUtil.TradeMoneyType.TradeOneShare)
            {
                double fDiff = myTradeStep.TransactionCosts + myTradeStep.LastBuyTransaction;
                myTradeStep.WinLoss += fDiff;
                

            }
        }
        private static void Evaluate_NumberOfShares_Buy( IDataItem myDataItem)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;

			switch (myTradeStep.TradeType)
			{
                case (CUtil.TradeType.BuyOneShare):
                    {
                        myTradeStep.NumberOfSharesTraded = 1;
                        break;
                    }
				case (CUtil.TradeType.Buy):
				{
					//1.2 normal buy 
					// Calculate the number of shares to buy:(do not include the transaction cost as influencing the number of shares to buy
					if(TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
					{
						myTradeStep.NumberOfSharesTraded = Convert.ToInt32(myTradeStep.Money / myTradeStep.FuturesContractValue) ;	
					
					}
					else
					{
						myTradeStep.NumberOfSharesTraded = Convert.ToInt32(myTradeStep.Money / myTradeStep.QuoteShare) ;	
					
					}
					break;
				}
				case (CUtil.TradeType.Buy10000):
				{
					//1.2 normal buy 
					// Calculate the number of shares to buy:(do not include the transaction cost as influencing the number of shares to buy
					if(TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
					{
						myTradeStep.NumberOfSharesTraded = Convert.ToInt32(myTradeStep.MaxMoneyForBuyPerShare/ myTradeStep.FuturesContractValue) ;	
					
					}
					else
					{
						myTradeStep.NumberOfSharesTraded = Convert.ToInt32(myTradeStep.MaxMoneyForBuyPerShare/ myTradeStep.QuoteShare) ;	
					
					}
					break;
				}
				case (CUtil.TradeType.Buy10000Again):
				{
					//1.2 normal buy 
					// Calculate the number of shares to buy:(do not include the transaction cost as influencing the number of shares to buy
					if(TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
					{
						myTradeStep.NumberOfSharesTraded = Convert.ToInt32(myTradeStep.MaxMoneyForBuyPerShare/ myTradeStep.FuturesContractValue) ;	
					
					}
					else
					{
						myTradeStep.NumberOfSharesTraded = Convert.ToInt32(myTradeStep.MaxMoneyForBuyPerShare/ myTradeStep.QuoteShare) ;	
					
					}
					break;
				}
				case (CUtil.TradeType.BuyShort):
				{
					if(TradeStepFactory.ProgramContext.Configuration.FuturesTrade)
					{
						myTradeStep.NumberOfSharesTraded = - myTradeStep.NumberOfShares;	
					
					}
					else
					{
						myTradeStep.NumberOfSharesTraded = - myTradeStep.NumberOfShares;	
					
					}
					break;
				}
					
				

			}
		}
	
		private static void EvaluateSellConditions(IDataItem myDataItem)
		{

            ITradeStep myTradeStep = myDataItem.TradeStep;


            EvaluateMoneySellConditions(myDataItem);
			//----------------------------------
			//evaluate second condition - if the indicators are OK
			if(myTradeStep.TradeTypeMoneyPossible != CUtil.TradeType.Nothing)
			{
                //IIndicators inds = myTradeStep.DataItem.DataClass.IndicatorsUnchecked;
                //Debug.Assert(inds != null && inds.Count > 0);

                myTradeStep.BuySellOccurs = TradeSystemStaticFunctions.Static_SellCondition
                    ( myTradeStep, myTradeStep.TradeSystem);
				if(myTradeStep.BuySellOccurs)
					myTradeStep.TradeType = myTradeStep.TradeTypeMoneyPossible;

			}

			if(myTradeStep.TradeTypeMoneyPossible == CUtil.TradeType.Nothing)
			{
				//-----------------------------------------------------------
				//options allowed ??
				if(myTradeStep.Money > myTradeStep.MinmalTransactionAmount)
				{
                    EvaluateMoneySellShortConditions(myDataItem);
//					if(myTradeStep.TradeTypeMoneyPossible != CUtil.TradeType.Nothing)
//					{
//						return;
//					}
				}

				//----------------------------------
				//evaluate second condition - if the indicators are OK
				if(myTradeStep.TradeTypeMoneyPossible != CUtil.TradeType.Nothing)
				{
                    Debug.Assert(myDataItem.DataClass.IndicatorsJustGetEm != null);
					if(TradeStepFactory.ProgramContext.Configuration.TradeShortSellOtherFile)
					{
                        myTradeStep.BuySellOccurs = TradeSystemStaticFunctions.Static_SellCondition
                            (myTradeStep, myTradeStep.TradeSystemForShortSell);
					}
					else
					{
                        myTradeStep.BuySellOccurs = TradeSystemStaticFunctions.Static_SellCondition
                            (myTradeStep, myTradeStep.TradeSystem);
					}
					
					if(myTradeStep.BuySellOccurs)
						myTradeStep.TradeType = myTradeStep.TradeTypeMoneyPossible;

				}
			}
			//return myTradeStep.BuySellOccurs;

			
		}
		private static void EvaluateMoneySellConditions( IDataItem myDataItem)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
			//--------------------------------------
			//Sell if
			//1. 

			myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Nothing;
			myTradeStep.TradeType  = CUtil.TradeType.Nothing;
		
			if(myTradeStep.NumberOfShares > 0)
			{
				myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Sell;
				return;
			}
			
		
		}
        private static void EvaluateMoneySellShortConditions( IDataItem myDataItem)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
			
			myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.Nothing;
			myTradeStep.TradeType  = CUtil.TradeType.Nothing;

			if(TradeStepFactory.ProgramContext.Configuration.TradeShortSellAllowed)
			{
				//if(myTradeStep.NumberOfShares == 0 )
				if(myTradeStep.NumberOfShares >= 0 )
				{
					myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.SellShort10000;
					return;
				}
				if(TradeStepFactory.ProgramContext.Configuration.TradeMoneyType == CUtil.TradeMoneyType.TradeWith10000AllTheTime)
				{
					myTradeStep.TradeTypeMoneyPossible = CUtil.TradeType.SellShort10000Again;
					return;
				}
			}
		}


        private static void AddTradeEvent(IDataItem myDataItem)
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
			TradeEvent te = new TradeEvent();
			te.Date = myTradeStep.Date;
			te.Number = myTradeStep.NumberOfSharesTraded;
			te.Money = myTradeStep.TransactionCosts;
			
			//te.ShareName = myTradeStep.S

            te.ShareName = myDataItem.DataClass.Name;
            te.ShareID = myDataItem.DataClass.ID;
			te.Quote = myTradeStep.ValueTotal;
			te.TradeType = myTradeStep.TradeType;

			//TradeEvent eventPrevious = null ;
            //if(myTradeStep.TradeEvents.Count > 0)
            //{
            //    eventPrevious = myTradeStep.TradeEvents[myTradeStep.TradeEvents.Count -1] as TradeEvent;
                
            //}
			

			myTradeStep.TradeEvents.Add(te);
			te.Performance = myTradeStep.PerformanceOfLastTrade;
            
            //probably more adjustments needed here for Buy1000 etc.
            if (te.TradeType == TradeType.Buy || te.TradeType == TradeType.Buy10000
                || te.TradeType == TradeType.Buy10000Again
                || te.TradeType == TradeType.BuyStopLoss
                || te.TradeType == TradeType.BuyOneShare)
                te.TradeEventType = TradeEventType.Investing;


		}

        public static void StepShareIncreaseDate(IDataItem myDataItem,ITradeSystem myTradeSystem, bool inOptimizationStep, IGrid myGrid, bool intraday)
		{
            try
            {
                if (!myDataItem.TradeStep.TradeSimulationInitiaded)
                {
                    Reset_Share_ForSimulation(myDataItem, myTradeSystem, inOptimizationStep,
                        TradeStepFactory.ProgramContext.Configuration.TradeMoneyType, intraday);

                    //this.tradeSimulation.ResetShare();//= myTradeStepFactory.ProgramContext.Trader_Simulation.TradeSimulation as TradeSimulation;
                    myDataItem.TradeStep.TradeSimulationInitiaded = true;
                }


                StepShare(myDataItem, myGrid, intraday);
                myDataItem.TradeStep.DateIndex++;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error in StepShareIncreaseDate " + ex.Message);
            }
		}


        private static void WriteTradeStepResult( IDataItem myDataItem, IGrid myGridTrade, bool intraday)
        {
            ITradeStep myTradeStep = myDataItem.TradeStep;

            TradeSystemStaticFunctions.SetIndicatorsString_InTradeStep(myTradeStep, myTradeStep.TradeSystem);

            switch (myTradeStep.TradeWriteMode)
            {
                case (TradeWriteModes.OnlyTrade):
                    {
                        if (myTradeStep.TradeType != TradeType.Nothing)
                        {

                            EndEvaluations(myTradeStep, intraday);
                            if (myGridTrade != null)
                                myGridTrade.AddRow_Single(myTradeStep, false);
                            //myGrid.WriteTradeInListView();
                        }
                        break;
                    }
                case (TradeWriteModes.EachTradeStep):
                    {
                        EndEvaluations(myTradeStep, intraday);
                        if (myGridTrade != null)
                            myGridTrade.AddRow_Single(myTradeStep, false);
                        //myGrid.WriteTradeInListView();
                        break;
                    }
                case (TradeWriteModes.EndResultShare):
                    {
                        //do nothing
                        break;
                    }
                default:
                    {
                        //do nothing
                        break;
                    }
            }
        }
        public static void StepShare( IDataItem myDataItem, IGrid myGrid, bool intraday) 
		{
            ITradeStep myTradeStep = myDataItem.TradeStep;
			
           

            if (myTradeStep.DateIndex < myDataItem.DataClass.QuoteCollection.Count)
			{
                Step(myDataItem);
				if(TradeSystemStaticFunctions.Abort || TradeStepFactory.ProgramContext.Configuration.TerminateAction )
				{
					return;
				}

                WriteTradeStepResult(myDataItem, myGrid, intraday);

				
				
			}
	

		}
        public static void WritePortfolioTradeInList( IDataItem myDataItem, ITradeStep myTradeStepPortfolio, IGrid myGrid, bool EndResultShare)
		{
            try
            {
                if (myDataItem != null)
                {
                    ITradeStep myTradeStep = myDataItem.TradeStep;

                    //take care !! the dateIndex is one value too high !!

                    if (EndResultShare)
                    {
                        myTradeStep.DateIndex = myTradeStep.DateMaxIndex;
                        myTradeStep.Date = myTradeStepPortfolio.Date;

                    }
                }

                TradeSystemStaticFunctions.SetTradeConditionsInTradeStep(myTradeStepPortfolio, myTradeStepPortfolio.TradeSystem);
                if (myGrid != null)
                    myGrid.AddRow_Single(myTradeStepPortfolio, false);
                Debug.WriteLine("--Portfolio simulation : " + myTradeStepPortfolio.IndicatorsString + " ; Performance " + myTradeStepPortfolio.Performance + " ; RElative " +
                    myTradeStepPortfolio.PerformanceRelative);

            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error in WritePortfolioTradeInList: " +  ex.Message);
            }
			
		}


        public static bool Reset_Share_ForSimulation(IDataItem myDataItem, ITradeSystem myTradeSystem, bool inOptimizationLoop, CUtil.TradeMoneyType tradeMoney, bool intraday)
		{
            if (myDataItem == null)
            {
                System.Windows.Forms.MessageBox.Show("No share selected ");
                return false;
            }
            //ITradeStep myTradeStep = myDataItem.TradeStep;
			
			try
			{
                //Debug.WriteLine("Resetting share for simulation : " + myDataItem.DataClass.Name);

				//reset trade system evaluating
				TradeSystemStaticFunctions.Abort = false;
                if (inOptimizationLoop)
                {
                    double f = myDataItem.DataClass.QuoteCollection[0].CLOSEc;
                    myDataItem.TradeStep.Reset(false, tradeMoney, f);
                }
                else
                {
                    if (!FirstInit_TradeStep(myDataItem, myTradeSystem))
                        return false;
                   
                    
                }

                ResetTradeStepToDates(myDataItem, intraday);
                return true;
				
			}
			catch(Exception exc)
			{
				Debug.Assert(false,"Error resetting share ",exc.Message);
				return false;
			}
		}
	

        /// <summary>
        /// dataholder - the main source of data
        /// </summary>
        public static IProgramContext ProgramContext
        {
            get
            {
                if (programContext == null)
                {
                    programContext = CStock.ProgramContext.Instance;
                }
                return programContext;

            }

        }
        /// <summary>
        /// evaluates a prognosis 
        /// </summary>
        /// <param name="MyDateIndex"></param>
        /// <returns></returns>
        //private static double EvaluateBuyPrognosis( IDataItem myDataItem)
        //{
        //    ITradeStep myTradeStep = myDataItem.TradeStep;
			
        //    myTradeStep.TradeWriteMode = TradeWriteModes.EachTradeStep;

        //    Debug.Assert(myDataItem.DataClass.IndicatorsJustGetEm != null);

        //    myTradeStep.BuySellOccurs = TradeSystemStaticFunctions.Static_BuyCondition
        //        (myTradeStep, myTradeStep.TradeSystem);


        //    if (myTradeStep.BuySellOccurs)
        //    {

        //        return myTradeStep.Prognosis;

        //    }
        //    else
        //    {
        //        return 0;
        //    }
        //}
        /// <summary>
        /// evaluates a prognosis 
        /// </summary>
        /// <param name="MyDateIndex"></param>
        /// <returns></returns>
        //private static double EvaluateSellPrognosis( IDataItem myDataItem)
        //{
        //    ITradeStep myTradeStep = myDataItem.TradeStep;
			
        //    myTradeStep.TradeWriteMode = TradeWriteModes.EachTradeStep;
        //    //myTradeStep.BuySellOccurs = this.EvaluateSellCondition(MyDateIndex);
        //    myTradeStep.BuySellOccurs = TradeSystemStaticFunctions.Static_SellCondition
        //        (myTradeStep, myTradeStep.TradeSystem);


        //    if (myTradeStep.BuySellOccurs)
        //    {

        //        return myTradeStep.Prognosis;

        //    }
        //    else
        //    {
        //        return 0;
        //    }
        //}
      
        public static bool FirstInit_TradeStep( IDataItem myDataItem, ITradeSystem tradeSystem)
        {
            try
            {
                if (myDataItem == null)
                {
                    System.Windows.Forms.MessageBox.Show("No data item selected ");
                    return false;
                }
                ITradeStep myTradeStep = myDataItem.TradeStep;


                myTradeStep.TradeSystem = tradeSystem;
                double f = myDataItem.DataClass.QuoteCollection[0].CLOSEc;
                myTradeStep.Init(true, TradeStepFactory.ProgramContext.Configuration.TradeMoneyType, f);

                Debug.WriteLine("Setting indicators in tradestep for share : " + myDataItem.DataClass.Name);
                if (!TradeSystemStaticFunctions.SetIndicatorsInTradeStep(myDataItem, TradeStepFactory.ProgramContext.Configuration.TradeMoneyType))
                {
                    System.Windows.Forms.MessageBox.Show("Share data / or volume missing for: " + myDataItem.Name + " - could not simulate");
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error initializing TradeStep: " + ex.Message);
                return false;
            }
            

        }
        public static bool FirstInit_Portfolio(IPortfolio myPortfolio, bool resetTradedItems, ITradeSystem ts)
        {
            ITradeStep myTradeStepPortfolio = myPortfolio.TradeStepPortfolio;
            myTradeStepPortfolio.TradeSystem = ts;

			
            // I do not need Indicators etc. in Portfolio tradeStep!
            myTradeStepPortfolio.TradeEvents = new System.Collections.ArrayList();
            //----------------------------------------------------------
            if (myPortfolio != null)
            {

                if (resetTradedItems)
                {
                    for (int i = 0; i < myPortfolio.DataItems.Count; i++)
                    {
                        myPortfolio.DataItems[i].Number = 0;
                        
                    }
                }
                myPortfolio.TradeEvents = new ArrayList();
                

            }
            myPortfolio.Serialize();

            //possibly need this later??
            ////--------------------------------------------------------------------------------
            ////read share data
            //for (int i = 0; i < myTradeStepPortfolio.Portfolio.DataItems.Count; i++)
            //{
            //    System.Windows.Forms.Application.DoEvents();
            //    IDataClass dc = myTradeStepPortfolio.Portfolio.DataItems[i].DataClass;
            //    if (dc.QuoteCollection.Count == 0)
            //        myTradeStepPortfolio.Portfolio.DeSerialize_DataClass(dc, this.tradeSimulation.Intraday);


            //}
            return true;

        }
        private static double CalcValuePortfInitialAllShares(IPortfolio portf)
        {
            double sum = 0f;
            for (int i = 0; i < portf.DataItems.Count; i++)
            {
                IDataClass dc = portf.DataItems[i].DataClass;
                if (dc.QuoteCollection.Count == 0)
                {
                    System.Windows.Forms.MessageBox.Show("No data is available (please download) : " + dc.ID);
                    return 0f;
                }
                else
                {
                    double f = dc.QuoteCollection[0].CLOSEc;
                    sum += f;
                }

            }
            return sum;
        }
        private static bool ResetPortfolioDates(IPortfolio myPortfolio)
        {


            DateTime dtMin = TradeStepFactory.ProgramContext.TradeEconomy.GetFirstDateForPortfolio(myPortfolio);
            DateTime dtMax = TradeStepFactory.ProgramContext.TradeEconomy.GetLastDateForPortfolio(myPortfolio);

            myPortfolio.TradeStepPortfolio.DateMin = TradeStepFactory.ProgramContext.Configuration.Dates.DateMinSimulation;
            myPortfolio.TradeStepPortfolio.DateMax = TradeStepFactory.ProgramContext.Configuration.Dates.DateMaxSimulation;

            if (myPortfolio.TradeStepPortfolio.DateMin < dtMin)
                myPortfolio.TradeStepPortfolio.DateMin = dtMin;

            if (myPortfolio.TradeStepPortfolio.DateMax > dtMax)
                myPortfolio.TradeStepPortfolio.DateMax = dtMax;

            //for(int i = 0; i <

            myPortfolio.TradeStepPortfolio.DateIndex = myPortfolio.TradeStepPortfolio.DateMinIndex;
            return true;

        }
        public static bool Reset_Portfolio_TradeStep(IPortfolio myPortfolio, ITradeSystem myTradeSystem,
            TradeWriteModes myTradeWriteMode, bool inOptimizationStep, CUtil.TradeMoneyType tradeMoney, bool intraday)
        {
            try
            {

                bool resetIndicators = false;
                if (!inOptimizationStep)
                {
                    FirstInit_Portfolio(myPortfolio, false, myTradeSystem);
                    resetIndicators = true;

                }
                else
                {
                    resetIndicators = false;
                }
                double f = CalcValuePortfInitialAllShares(myPortfolio);
                if (f == 0f)
                    return false;


                myPortfolio.TradeStepPortfolio.Init(resetIndicators, TradeStepFactory.ProgramContext.Configuration.TradeMoneyType, f);


                myPortfolio.TradeStepPortfolio.FuturesTrade = TradeStepFactory.ProgramContext.Configuration.FuturesTrade;
                myPortfolio.TradeStepPortfolio.MoneyStart = myPortfolio.TradeStepPortfolio.MaxMoneyForBuyPerPortfolio;
                myPortfolio.TradeStepPortfolio.Money = myPortfolio.TradeStepPortfolio.MaxMoneyForBuyPerPortfolio;


                ResetPortfolioDates(myPortfolio);

                //--------------------------------------------------------
                //now set single share trade steps:


                Reset_Portfolio_SharesN(myPortfolio, myTradeSystem,
                    inOptimizationStep, tradeMoney, intraday);

                myPortfolio.TradeStepPortfolio.TradeWriteMode = myTradeWriteMode;

                return true;


            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error resetting portfolio; " + ex.Message);
                return false;
                //occurs during class creation - do nothing
            }
        }

        public static void Reset_Portfolio_SharesN(IPortfolio myPortfolio, ITradeSystem myTradeSystem, bool inOptimizationStep, 
            CUtil.TradeMoneyType tradeMoney, bool intraday)
        {
            for (int i = 0; i < myPortfolio.DataItems.Count; i++)
            {
                IDataItem di = myPortfolio.DataItems[i];
                            
                if (inOptimizationStep)
                {

                    //myTradeStep.Date = myTradeStep.DateMin;
                    //myTradeStep.DateIndex = myTradeStep.DataItem.DataClass.IndexFindGreaterThan(myTradeStep.DateMin);
                    //myTradeStep.DateIndex = myTradeStep.DateMinIndex;
                    Reset_Share_ForSimulation(di, myTradeSystem, inOptimizationStep, tradeMoney, intraday);

                }
                else
                {
                    //FirstInit_TradeStep();
                    Reset_Share_ForSimulation(di, myTradeSystem, inOptimizationStep, tradeMoney, intraday);

                   

                }

            }
           

        }

	}
}
